package com.tianji.learning.util;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;
import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
@AllArgsConstructor(staticName = "of")
public class DelayTask<T> implements Delayed, Serializable {
    private Long deadLineNacos;
    private T data;

    public DelayTask(Duration deadLineNacos, T data) {
        this.deadLineNacos =System.nanoTime()+ deadLineNacos.toNanos();
        this.data = data;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        //获取每个队列的任务以及他们还有多久执行
        return unit.convert(Math.max(deadLineNacos-System.nanoTime(),0),TimeUnit.NANOSECONDS);
    }

    //对延迟队伍进行排序
    @Override
    public int compareTo(Delayed o) {
        long diff=this.getDelay(TimeUnit.NANOSECONDS)-o.getDelay(TimeUnit.NANOSECONDS);
        return diff>0?1:diff==0? 0: -1;
    }
}
